package tech.summerly.weather.component.adapter

import android.support.v7.widget.RecyclerView
import android.view.ViewGroup
import kotlinx.android.synthetic.main.item_hourly_trend.view.*
import tech.summerly.weather.R
import tech.summerly.weather.data.bean.HourlyForecast
import tech.summerly.weather.data.remote.CaiYunService
import tech.summerly.weather.util.Aqi
import tech.summerly.weather.util.ViewHolder

class HourlyTrendAdapter : RecyclerView.Adapter<ViewHolder>() {

    private var hourlyForecast: HourlyForecast? = null

    fun setData(hourlyForecast: HourlyForecast) {
        this.hourlyForecast = hourlyForecast
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val createView = ViewHolder.createView(R.layout.item_hourly_trend, parent)
        return ViewHolder(createView)
    }

    override fun getItemCount(): Int = hourlyForecast?.temperature?.size ?: 0

    override fun onBindViewHolder(holder: ViewHolder, position: Int) = with(holder.itemView) {
        val hourlyForecast = hourlyForecast ?: return@with

        val skyIcon = CaiYunService.SkyCon.getSkyIcon(hourlyForecast.skycon[position].value)
        imageSky.setImageResource(skyIcon)

        val time = hourlyForecast.skycon[position].datetime.substringAfterLast(" ")
        textHour.text = time

        val aqi = hourlyForecast.aqi[position].value.toInt()
        val level = Aqi.from(aqi)
        textAqi.text = "%d".format(aqi)
        textAqi.setBackgroundColor(level.color())
        Unit

    }

}